﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using User.API.Models;

namespace User.API.Filters
{
    public class GlobalExceptionFilter
        : IExceptionFilter
    {
        private readonly IHostingEnvironment _env;
        private readonly ILogger<GlobalExceptionFilter> _logger;
        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger, IHostingEnvironment env)
        {
            _logger = logger;
            _env = env;
        }
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                var excep = context.Exception;
                var controllerName = context.RouteData.Values["controller"];
                var actionName = context.RouteData.Values["action"];
                string tempMsg = $"在请求controller[{controllerName}] 的 action[{actionName}] 时产生异常[{excep.Message}]";
                _logger.LogError(tempMsg);//Log.

                //if (excep.GetType()==typeof(UserOperationException))
                //{
                //    context.Result = new BadRequestObjectResult(excep);
                //}
                //else
                //{
                //    context.Result = new InternalServerErrorObjectResult("服务器内部错误，请联系管理员");
                //}
                if (_env.IsDevelopment())
                {
                    context.Result = new JsonResult(new AjaxResult(DoResult.Failed, "系统出现异常，请联系管理员", excep.Message));//In development,output exception message.
                }
                else
                {
                    context.Result = new JsonResult(new AjaxResult(DoResult.Failed, "系统出现异常，请联系管理员"));
                }
                context.ExceptionHandled = true;//Tag it is handled.
            }
        }
    }

    internal class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object val)
            :base(val)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
}
